﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DAO;

namespace TAM_SPORT
{
    public partial class EditProperties : Form
    {
        ProductDao dao;
        private int id;
        public EditProperties(int id)
        {
            InitializeComponent();
            dao = new ProductDao();
            loadCbx();
            cbxPro.SelectedIndex = 0;
            this.id = id;
            init(id);
        }

        private void loadCbx()
        {
            DataTable table = dao.getProperties("");
            cbxPro.DataSource = table;
            DataRow row = table.NewRow();
            row["ID"] = -1;
            row["NAME"] = "Chọn dụng cụ";
            table.Rows.InsertAt(row, 0);
            cbxPro.DisplayMember = "NAME";
            cbxPro.ValueMember = "ID";
        }

        private void init(int id)
        {
            DataRow row = dao.getPropertiesById(id);
            if (row != null)
            {
                cbxPro.SelectedValue = int.Parse(row["PRO_ID"].ToString());
                nbQuantity.Value = int.Parse(row["QUANTITY"].ToString());
            }
        }
        private void btnsave_Click(object sender, EventArgs e)
        {
            if (cbxPro.SelectedIndex >= 1 && nbQuantity.Value >= 1)
            {
                if (dao.updateProperties(id, int.Parse(cbxPro.SelectedValue.ToString()), (int)nbQuantity.Value))
                {
                    Result r = new Result(UserConstant.SAVE_SUCCESSFUL);
                    r.ShowDialog();
                    r.Dispose();
                    this.Dispose();
                }
                else
                {
                    Error er = new Error(UserConstant.SAVE_FAIL);
                    er.ShowDialog();
                    er.Dispose();
                }
                
            }
            else
            {
                Error er = new Error(UserConstant.INPUT_VALIDATE);
                er.ShowDialog();
                er.Dispose();
            }
            
        }

        private void cbxPro_SelectedValueChanged(object sender, EventArgs e)
        {
            if (cbxPro.SelectedIndex >= 1)
            {
                try
                {

                    string s = cbxPro.SelectedValue == null ? "" : dao.getUnitNameofProduct(int.Parse(cbxPro.SelectedValue.ToString()));
                    lblUnitName.Text = s;
                }
                catch
                {
                    lblUnitName.Text = "";
                }

            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Dispose();
        }
    }
}
